package com.keba.basic.encrypt.advice;

import com.keba.basic.encrypt.annotation.EncryptBody;
import com.keba.basic.encrypt.codec.SecurityProcessor;
import com.keba.basic.encrypt.config.properties.SecurityProperties;
import com.keba.basic.encrypt.exception.EncryptBodyFailException;
import com.keba.basic.encrypt.util.CommonUtils;
import cn.hutool.core.codec.Base64Encoder;

import cn.hutool.core.util.CharsetUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;


/**
 * 响应数据的加密处理<br>
 * 本类只对控制器参数中含有<strong>{@link org.springframework.web.bind.annotation.ResponseBody}</strong>
 * 或者控制类上含有<strong>{@link org.springframework.web.bind.annotation.RestController}</strong>
 *
 * @author licoy.cn
 * @version 2018/9/4
 * @see ResponseBodyAdvice
 */
@Order(1)
@ControllerAdvice
@Slf4j
@AllArgsConstructor
public class EncryptResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    private final ObjectMapper objectMapper;

    private final SecurityProperties securityProperties;

    private final SecurityProcessor securityProcessor;


    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (!securityProperties.isEnable()) {
            return false;
        }
        Class<?> declaringClass = returnType.getDeclaringClass();
        if (this.hasEncryptAnnotation(declaringClass)) {
            return true;
        }
        Method method = returnType.getMethod();
        if (method != null) {
            Class<?> returnValueType = method.getReturnType();
            return this.hasEncryptAnnotation(method) || this.hasEncryptAnnotation(returnValueType);
        }
        return false;
    }

    private boolean hasEncryptAnnotation(AnnotatedElement annotatedElement) {
        if (annotatedElement == null) {
            return false;
        }
        return annotatedElement.isAnnotationPresent(EncryptBody.class);
    }

    @Override
    public String beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return null;
        }
        String str = CommonUtils.convertToStringOrJson(body, objectMapper);
        Method method = returnType.getMethod();
        if (method != null) {
            // 从方法上
            if (method.isAnnotationPresent(EncryptBody.class)) {
                return Base64Encoder.encode(securityProcessor.encrypt(str.getBytes(CharsetUtil.charset(securityProperties.getCharset()))));
            }
        }

        // 从声明类上
        AnnotatedElement annotatedElement = returnType.getDeclaringClass();
        if (annotatedElement.isAnnotationPresent(EncryptBody.class)) {
            return Base64Encoder.encode(securityProcessor.encrypt(str.getBytes(CharsetUtil.charset(securityProperties.getCharset()))));
        }
        throw new EncryptBodyFailException();
    }
}
